<?header('Content-type: application/xml; charset="utf-8"',true);
include "detect_utf_encoding.php";



$fileurl=$_GET['smi'];


print_header();


$url="http://";
//$fileurl=rawurldecode($fileurl);
$fileurl=str_replace("http://", "", $fileurl);
$explode_path=explode("/",$fileurl);

foreach($explode_path as $path){
	 $url= $url.rawurlencode($path)."/";
}    		
$url=substr($url,0,-1);

$isok=connect_test($url);
if($isok!=null){

		print  <<< END_HEADER

<p begin="00:00:00.00"><div>{$url}자막이 없습니다</div></p>
END_HEADER;
	print_footer();
}
else {
	$encoding=detect_utf_encoding($url);
	$smi_original_text=charset_encoding(file_get_contents($url),$encoding);
	$smi_encoded=explode( "\n", $smi_original_text);

	$length=sizeof($smi_encoded);
	$firstflag=true;
	$smi=array();
	for ($i=0;$i <= $length-1;$i++){
			
		$result1=findSync($smi_encoded[$i]);
		//echo print_r( $result1);
		if($result1[2]!=null){
			$firstflag=false;
			if($smi['from_time']==null){			
				$smi['from_time']=convertTime($result1[2]);
				$smi['content']=$smi['content'].$result1[3];			
				continue;
			}else{
				$smi['to_time']=convertTime($result1[2]);
				$smi['content']=$smi['content'].$result1[1];
				$nextContent=$result1[3];					
			}
		}elseif(!$firstflag){			
			$smi['content']=$smi['content'].$smi_encoded[$i];
		}

				
		if($smi['to_time']!=null){
			print_line($smi["from_time"], processContent($smi['content']) );
			$smi=array("from_time"=>$smi["to_time"],"content"=>$nextContent);
		}
	
	}



	print_footer();		
}
function convertTime($time){
	return $time/1000;
}
function connect_test($url)  
{

	// 000 : only http://
	// 001 checkdnsrr error
	// 002 fsockopen error
	// other : http return code

	if ($url == "http://") return "000";
	$parsed = parse_url($url);
	$scheme = $parsed["scheme"];
	$host = $parsed["host"];
	$path = $parsed["path"];

	if(eregi("http",$scheme)){
		$port=80;	
	}
	if(eregi("ftp",$scheme)){
		$port=21;
		return;
	}
	if($parsed["port"])
		$port = $parsed["port"];

	if (!$path) $path = "/";

	if (!(checkdnsrr($host,"A"))) return "도메인을 찾을수 없습니다.";

	$fp = fsockopen ($host, $port,$errno, $errstr, 10) ;
	if (!$fp) return "유효하지 않은 url입니다.";

	fputs($fp,"GET $path HTTP/1.1\r\nHost: {$host}\r\nConnection: close\r\n\r\n");  
	$line = fgets($fp, 1024);  
		 
	if (!eregi( "(200 OK)", $line)) {
		//echo $url."<br>".$path;
		 $return =   "유효하지 않은 url입니다.";
	}
	else {
		$return = null;
	}

	fclose($fp);  
	return $return;
}  

function findSync($str) {
	$pattern='/(.*)<sync start=(\d+)>(.*)/i';
	preg_match($pattern,$str,$matches);
	return $matches;
}




function processContent($text){
	//$text=charset_encoding($text);
	/*$document = new SimpleDocument($text);
	$child_nodes=$document->child_nodes();
	foreach($child_nodes as $node){
		//if($$node->get_attribute("color"))
		if($node->node_name()=="p"){
			foreach($node->child_nodes() as $no){
				echo $no->node_name()."/".$no->get_node_value()."\n";
			}
		}
		if($node->node_name()=="font"){
			

		}

	}*/
	

	$text=removeTag($text);
	$text=fontTag($text);

	$text="{$text} <![CDATA[ ]]>";
	//$text=preg_replace("/<span>\s?<\/span>/i",'',$text);
	//$text=preg_replace('/(.*)<\/span>(.*)/i','${1}</span><span><![CDATA[${2}]]></span>',$text);
	
	/*preg_match('/<\/span>/',$text,$matches);

	if($matches[0]==null){
		
		//$text="<span><![CDATA[".$text."]]></span>";
	}*/
	return $text;
}
function fontTag($text){
	//preg_match('/<(\w+)[^<>]*\scolor=[\"]?[#]?(\w+)[\"]?[^<>]*>/i',$text,$match);
	//echo $colortag=$match[1];
	$text=preg_replace("/<br[^<>]*>/i",'|br|',$text);
	$text=preg_replace("/<font[^<>]*\scolor=[\"]?[#]?(\w+)[\"]?[^<>]*>([^<>]*)<\/font>/ie",'" <span tts:color=\"".colorcode("${1}")."\"> ${2} </span>"',$text);
	$text=preg_replace("/<font[^<>]*\scolor=[\"]?[#]?(\w+)[\"]?[^<>]*>([^<>\]]*)/ie",'" <span tts:color=\"".colorcode("${1}")."\"> ${2} </span>"',$text);
	$text=preg_replace("/\|br\|<\/span>/i",'</span> <br /> ',$text);
	//$text=preg_replace("/<span>\|br\|<\/span>/i",'<br /><span></span>',$text);
/*<u> tts:textDecoration=”underline*/
	$text=preg_replace("/\|br\|/i",' <br /> ',$text);
	$text=preg_replace("/\|([^a-zA-Z\/]+)\|/i",' 「${1}」 ',$text);
	$text=preg_replace("/<\/?font[^<>]*>/i",'',$text);
	$text=preg_replace("/\\\'/","'",$text);
		$text=preg_replace("/<span[^<>]*>\s*<\/span>/ie",'" "',$text);
	//$text=preg_replace('/<\/{$colortag}>/','</span>',$text);
	return $text;
}
function colorcode($in){
	preg_match('/[0-9a-f]{6}/i',$in,$matches);
/*"transparent" = #00000000 
"black"=#000000FF 
"silver"=#C0C0C0FF 
"grey"=#808080FF 
"white"=#FFFFFFFF 
"maroon"=#800000FF 
"red"=#FF0000FF 
"purple"=#800080FF 
"fuchsia"("magenta")= #FF00FFFF 
"green"=#008000FF
"lime"=#00FF00FF
"olive"=#808000FF 
"yellow"=#FFFF00FF 
"navy"=#000080FF 
"blue"=#0000FFFF 
"teal"=#008080FF 
"aqua"("cyan")=#00FFFFFF
*/
	if($matches[0]==null){
		switch(strtolower($in)){
			case "black":
				$in="000000";
				break;
			case "silver":
				$in="C0C0C0";
				break;
			case "grey":
				$in="808080";
				break;
			case "white":
				$in="FFFFFF";
				break;
			case "maroon":
				$in="800000";
				break;
			case "red":
				$in="FF0000";
				break;
			case "purple":
				$in="800080";
				break;
			case "fuchsia":
				$in="FF00FF";
				break;
			case "green":
				$in="008000";
				break;
			case "lime":
				$in="00FF00";
				break;
			case "olive":
				$in="808000";
				break;
			case "yellow":
				$in="FFFF00";
				break;
			case "navy":
				$in="#000080";
				break;
			case "blue":
				$in="0000FF";
				break;
			case "teal":
				$in="008080";
				break;
			case "aqua":
			case "cyan":
				$in="00FFFF";
				break;

		}
	}
	return "#".strtoupper($in);
}
function removeTag($text){
	//$text=preg_replace('/<\/(?!span)(?!br).*>/i','',$text);

	$text = str_replace("\n","",$text);
	$text = str_replace("\r","",$text);
	$text=preg_replace('/<([^a-zA-Z\/]+)>/i','|${1}|',$text);
	$text=strip_tags($text, '<br><font>');
/*	$text=preg_replace('/<\/?p[^>]*>/i','',$text);
	$text=preg_replace("/<\/?ruby[^<>]*>/i",'',$text);
	$text=preg_replace("/<\/?rb[^<>]*>/i",'',$text);
	$text=preg_replace("/<\/?rt[^<>]*>/i",'',$text);
	$text=preg_replace("/<\/?rp[^<>]*>/i",'',$text);
	$text=preg_replace("/<\/?i[^<>]*>/i",'',$text);
	$text=preg_replace("/<\/?u[^<>]*>/i",'',$text);*/
	$text=preg_replace('/&nbsp;?/i',' ',$text);
	///<([^>]+|[^s]+|[^b]+)>/i
	return $text;
}

function print_line($from_time,$content) {
		$xml = "<p begin=\"".$from_time."\">";
		$xml = $xml.$content;
		$xml = $xml."</p>\n";
		print $xml;
}
function charset_encoding($str,$from_encoding){
	if($from_encoding=="ANSI")
		return iconv("CP949","UTF-8", $str);
	else if($from_encoding=="UTF-8")
		return $str;
	else if($from_encoding=="UTF-16LE")
		return iconv("UNICODE","UTF-8", $str);
		
}

function print_footer()
{
	print <<< END_HEADER
    </div>
  </body>
</tt>
END_HEADER;

	
}



function print_header()
{
	print  <<< END_HEADER
<?xml version="1.0" encoding="UTF-8"?>
<tt xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling">
  <body>
    <div>


END_HEADER;

}
?>